#include <network.h>
#include <data.h>
#include <stdio.h>
#include <string.h>
#include <time.h> // time_t struct tm
#include <unistd.h>

static int ParsePacket(char *packet, DATA data[], int *datanum)
{
	char *cp, *cp1, *cp2, *cp3;
	int i;

	if( !packet || (packet=strstr(packet, "\n ")) == NULL )
		return -1;

	packet += 1;

	i = MAX_NUM_OF_DATA-1;
	while(*packet)
	{
		if( (cp=strchr(packet, '\n')) != NULL )
			*cp = '\0';

		while( (cp1=strchr(packet, '\"')) != NULL )
		{
			if( (cp2=strchr(cp1+1, '\"')) == NULL )
				return -1;

			*cp1 = *cp2 = ' ';
			cp1 += 1;

			while( *cp1 != ' ' )
			{
				if( *cp1 == ',' )
				{
					cp3 = cp1;
					while(1)
					{
						*cp3 = *(cp3+1);
						cp3 += 1;
						if(cp3 == cp2)
							break;
					}
				}
				cp1 += 1;
			}
		}

		while( (cp1=strchr(packet, ',')) != NULL )
			*cp1 = ' ';

		sscanf(packet, "%d/%d/%d %d %d %lf %lf %lf %lf"
			, &data[i].year, &data[i].month, &data[i].day
			, &data[i].trade_vol, &data[i].trade_money
			, &data[i].open, &data[i].high, &data[i].low, &data[i].close
			);
		data[i].year += 1911;
		i -= 1;

		packet += strlen(packet) + 1;
	}


	if( i < MAX_NUM_OF_DATA-1 )
	{
		memcpy(&data[*datanum], &data[i+1], sizeof(DATA)*(MAX_NUM_OF_DATA-1-i));
		*datanum += MAX_NUM_OF_DATA-1-i;
	}

	return 0;
}

int GetHistory(char *quote, DATA data[], int *datanum)
{
	char buffer[65535];
	char *host = "www.twse.com.tw";
	time_t t;
	struct tm *tm_p;
	int sockfd, year, month, i, ret = 0;

	time(&t);
	tm_p = localtime(&t);

	year = tm_p->tm_year+1900;
	month = tm_p->tm_mon+1;

	i=0;
	printf("0000/00");
	while(1)
	{
		printf("\b\b\b\b\b\b\b%04d/%02d", year, month);
		if( i == 0)
		{
			if( CreateConnection(&sockfd, host) < 0 )
			{
				ret = -1;
				break;
			}
		}

		sprintf(buffer,
			"GET /ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report%04d%02d/%04d%02d_F3_1_8_%s.php&type=csv HTTP/1.1\r\n"
			"Host: %s\r\n\r\n"
			,year,month,year,month,quote
			,host
		);
		if( SendData(sockfd, buffer) < 0 )
		{
			CloseConnection(&sockfd);
			ret = -1;
			break;
		}

		if( ReceiveData(sockfd, buffer, sizeof(buffer)) < 0 || !memcmp(buffer, "div>", 4) || !memcmp(buffer, "intval", 6) )
		{
			CloseConnection(&sockfd);
			break;
		}

		ParsePacket(buffer, data, datanum);

		year = (month==1)?(year-1):(year);
		month = (month==1)?12:(month-1);

		if(i<48)
			i += 1;
		else
		{
			CloseConnection(&sockfd);
			i = 0;
		}
	}

	printf("\b\b\b\b\b\b\b OK    \n");
	return 0;
}
